package com.hui.security.common.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.util.Date;

/**
 * <b><code>JwtUtil</code></b>
 * <p/>
 * Description:
 * <p/>
 * <b>Creation Time:</b> 2019/1/5 14:51.
 *
 * @author HuWeihui
 */
public class JwtUtil {
    private static final long EXPIRE_TIME = 30 * 60 * 1000;

    private static final String ACCOUNT_SIGN = "account";

    /**
     * 校验token
     *
     * @param token
     * @param account
     * @param password
     * @return
     */
    public static boolean verify(String token, String account, String password) {
        try {
            //根据密码生成JWT效验器
            Algorithm algorithm = Algorithm.HMAC256(password);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim(ACCOUNT_SIGN, account)
                    .build();
            //效验TOKEN
            verifier.verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }

    /**
     * 获取用户账号
     * @param token
     * @return
     */
    public static String getUserAccount(String token) {
        DecodedJWT jwt = JWT.decode(token);
        String account = jwt.getClaim(ACCOUNT_SIGN).asString();
        return account;
    }

    /**
     * 生成token签名
     *
     * @param account
     * @param password
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String sign(String account, String password) throws UnsupportedEncodingException {
        return sign(account, password, new Date((System.currentTimeMillis() + EXPIRE_TIME)));
    }

    /**
     * 生成token签名
     *
     * @param account
     * @param password
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String sign(String account, String password, Date expireDate) throws UnsupportedEncodingException {
        Algorithm algorithm = Algorithm.HMAC256(password);
        // 生成token签名
        String sign = JWT.create()
                .withClaim(ACCOUNT_SIGN, account)
                .withExpiresAt(expireDate)
                .sign(algorithm);
        return sign;
    }


}
